import { BMapWX } from "@/utils/bmap-wx.min.js"
import { baiduAK } from '@/common/env/index.js'

const bmap = new BMapWX({
  ak: baiduAK
})
const states = {
	vuex_address:'长沙'
}
const actions = {
  /**
   * 根据地址描述获得坐标信息
   */
  getPoint({ commit }, params) {
    const { cityName, detailAddress } = params
    return new Promise((resolve, reject) => {
      var myGeo = new window.BMap.Geocoder()
      myGeo.getPoint(detailAddress, (point) => {
          if (point) {
            resolve({
              longitude: point.lng,
              latitude: point.lat,
            })
          } else {
            reject('解析失败')
          }
        }, cityName )
    })
  },

  //根据地址 取得经纬度，坐标
  getAddressGps ({ commit }, params) {
    return new Promise((resolve, reject) => {
      const { cityName, detailAddress, that } = params
      //#ifdef H5
      that.$jsonp(`https://api.map.baidu.com/geocoding/v3/?address=${detailAddress}&output=json&ak=VmZWMiTQDW8BQ0nmECODxnmiOOiHhfgW`).then(result => {
        let location = {}
        location.longitude = result.result.location.lng
        location.latitude = result.result.location.lat
        resolve(location)
      });
      //#endif

      //#ifdef MP-WEIXIN
      const success = function(res) {
        resolve({
          longitude: res.result.location.lng,
          latitude: res.result.location.lat
        })
      }
      const fail = function(res) {
        reject('解析失败')
      }
      bmap.geocoding({ 
        address: detailAddress, 
        fail: fail, 
        success: success,
      });
      //#endif
    })
  },

  //根据经纬度获取地址
  getAddress ({ commit }, params) {
	return  new Promise((resolve, reject) => {
      const { latitude, longitude, that } = params
      //#ifdef H5
      that.$jsonp(`https://api.map.baidu.com/reverse_geocoding/v3/?ak=VmZWMiTQDW8BQ0nmECODxnmiOOiHhfgW&location=${latitude},${longitude}&output=json&coordtype=wgs84ll`).then(result => {
        resolve(result.result)
      });
      //#endif

      //#ifdef MP-WEIXIN
      bmap.regeocoding({
        location: `${latitude},${longitude}`,
        fail(res) {
          reject('解析失败')
        },
        success(res) {
          resolve(res.originalData.result)
        },
      })
      //#endif
    })
  },
}

export default {
  namespaced: true,
  actions,
  states
}